package com.clp.protocol.modbus_tcp.mb_frame.mb_body.mb_data.resp_ok;

import com.clp.protocol.core.utils.ByteUtil;
import com.clp.protocol.modbus_tcp.definition.ConstVal;
import com.clp.protocol.modbus_tcp.definition.MbByteOrder;
import com.clp.protocol.modbus_tcp.mb_frame.mb_body.mb_data.RespOkMbData;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.nio.ByteOrder;
import java.util.Objects;

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ForceMultiCoilsRespOkMbData implements RespOkMbData {
    /**
     * 设置起始地址
     */
    private int startAddr;
    /**
     * 设置数量
     */
    private int num;

    @Override
    public ForceMultiCoilsRespOkMbData initBy(ByteBuf buf) {
        byte[] startAddrBytes = new byte[ConstVal.START_ADDR_LEN]; buf.readBytes(startAddrBytes);
        this.startAddr = MbByteOrder.startAddrOrder == ByteOrder.BIG_ENDIAN ?
                ByteUtil.bytes2ToIntBE(startAddrBytes) : ByteUtil.bytes2ToIntLE(startAddrBytes);
        byte[] numBytes = new byte[ConstVal.NUM_LEN]; buf.readBytes(numBytes);
        this.num = MbByteOrder.numOrder == ByteOrder.BIG_ENDIAN ?
                ByteUtil.bytes2ToIntBE(numBytes) : ByteUtil.bytes2ToIntLE(numBytes);
        return this;
    }

    @Override
    public boolean isValid() {
        if (startAddr < 0 || startAddr > 0xFFFF) return false;
        return num >= 0 && num <= 0xFF;
    }

    @Override
    public void writeTo(ByteBuf buf) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String toString() {
        return "起始地址：" + startAddr + ", 数量：" + num;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ForceMultiCoilsRespOkMbData that = (ForceMultiCoilsRespOkMbData) o;
        return startAddr == that.startAddr && num == that.num;
    }

    @Override
    public int hashCode() {
        return Objects.hash(startAddr, num);
    }
}
